package vip.zhenzicheng.test.juc.atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @author zhenzicheng
 * @date 2022-09-06 21:31
 */
@Slf4j
public class AtomicMarkableReferenceCase {

  static AtomicMarkableReference<Integer> markableReference = new AtomicMarkableReference<>(100, false);

  public static void main(String[] args) {
    new Thread(() -> {
      boolean marked = markableReference.isMarked();
      log.info("当前线程: {}, 默认标识: {}", Thread.currentThread().getName(), marked);
      // 等待t2开始
      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      markableReference.compareAndSet(100, 1000, marked, !marked);
      log.info("结果为: {}", markableReference.getReference());
    }, "t1").start();

    new Thread(() -> {
      boolean marked = markableReference.isMarked();
      log.info("当前线程: {}, 默认标识: {}", Thread.currentThread().getName(), marked);
      // 等待t1结束
      try {
        TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      boolean b = markableReference.compareAndSet(100, 2000, marked, !marked);
      log.info("{}线程, CAS 状态: {}", Thread.currentThread().getName(), b);
      log.info("结果为: {}", markableReference.getReference());
    }, "t2").start();
  }
}
